package com.sskj.run.ui.fragment;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.sskj.boom.bean.EscapeBean;
import com.sskj.boom.bean.GameStatus;
import com.sskj.boom.widget.BoomView;
import com.sskj.common.adapter.MyFragmentPagerAdapter;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.ImgUtil;
import com.sskj.common.util.LanguageUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.fall.FallObject;
import com.sskj.fall.SurfaceFallView;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.TabItem;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.box.LiveDataBus;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.AppCircleCheckUtil;
import com.sskj.lib.util.CommonUtil;
import com.sskj.lib.util.ImageUtil;
import com.sskj.lib.util.NumberUtil;
import com.sskj.run.R;
import com.sskj.run.R2;
import com.sskj.run.adapter.QiangjinSpinnerAdapter;
import com.sskj.run.bean.CoinInfo;
import com.sskj.run.bean.MainMenuBean;
import com.sskj.run.bean.SocketBean;
import com.sskj.run.bean.StockBloomBean;
import com.sskj.run.component.DaggerUserDataComponent;
import com.sskj.run.presenter.QiangjinFragmentPresenter;
import com.sskj.run.widget.FallingView;
import com.yhao.floatwindow.FloatWindow;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

@Route(path = RConfig.RUN_FRAGMENT_QIANGJIN)//抢金
public class QiangjinFragment extends BaseFragment<QiangjinFragmentPresenter> {

    @BindView(R2.id.commonTabLayoutCoin)
    CommonTabLayout commonTabLayoutCoin;
    @BindView(R2.id.ivBeBanker)
    ImageView ivBeBanker;
    @BindView(R2.id.slidingTabLayout)
    SlidingTabLayout slidingTabLayout;
    @BindView(R2.id.viewPager)
    ViewPager viewPager;
    @BindView(R2.id.boomView)
    BoomView boomView;
    @BindView(R2.id.rl_asset_record)
    RelativeLayout rlAssetRecord;
    @BindView(R2.id.rl_banker_jackpot)
    RelativeLayout rlBankerJackpot;
    @BindView(R2.id.btn_bet)
    Button btnBet;
    @Inject
    UserViewModel userViewModel;
    @BindView(R2.id.et_bet)
    EditText etBet;
    @BindView(R2.id.et_run_away)
    EditText etRunAway;
    @BindView(R2.id.tv_max)
    TextView tvMax;
    @BindView(R2.id.tv_award_poll)
    TextView tvAwardPoll;
    @BindView(R2.id.tv_min)
    TextView tvMin;
    @BindView(R2.id.tv_divide)
    TextView tvDivide;
    @BindView(R2.id.tv_multiply)
    TextView tvMultiply;
    @BindView(R2.id.tv_earn)
    TextView tvEarn;
    @BindView(R2.id.tv_chance)
    TextView tvChance;
    @BindView(R2.id.tv_money)
    TextView tvMoney;
    @BindView(R2.id.spinner)
    Spinner spinner;
    @BindView(R2.id.tv_user_agreement)
    TextView tvUserAgreement;
    @BindView(R2.id.tv_privacy_agreement)
    TextView tvPrivacyAgreement;
    @BindView(R2.id.tv_help_center)
    TextView tvHelpCenter;
    @BindView(R2.id.tv_now_value)
    TextView tv_now_value;
    @BindView(R2.id.tv_app_download)
    TextView tvAppDownload;
    @BindView(R2.id.tv_show_run)
    TextView tv_show_run;
    @BindView(R2.id.iv_money_type)
    ImageView iv_money_type;
    @BindView(R2.id.iv_boom)
    SurfaceFallView iv_boom;
    @BindView(R2.id.iv_boom_handred)
    ImageView iv_boom_handred;
    @BindView(R2.id.tv_clear_wanfa)
    ImageView tv_clear_wanfa;
    @BindView(R2.id.ivBg)
    ImageView ivBg;
    @BindView(R2.id.ll_wanfa_anim)
    LinearLayout ll_wanfa_anim;
    private UserData userData;
    private SlimAdapter slimAdapter;

    private List<EscapeBean> escapeBeans;

    private AnimationDrawable boomAnimationDrawable;
    private AnimationDrawable handredAnima;
    private AnimationDrawable wanFaAnim;

    private ArrayList<MainMenuBean> mainMenuBeans = new ArrayList<>();
    private QiangjinSpinnerAdapter spinnerAdapter;

    private String betType;

    //是否下注
    private boolean isBet;
    //是否逃跑
    private boolean isRun;
    //是否爆炸
    private boolean isBoom;
    //是否预约
    private boolean isSubscribe;
    //下注金额
    private String betMoney;
    //预约下注是否已请求
    private boolean isSubscriCommit;
    //预约下注金额
    private String subscribeBetMoney;
    //预约逃跑倍数
    private String subscribeBetValue;
    //预约下注币种
    private String subscribeBetType;
    //默认逃跑倍数tv_money
    private float betValue;

    private List<CoinInfo> coinInfoList;
    private CoinInfo coinInfo;
    private Disposable etBetDispo;
    private Disposable etRunAwayDispo;
    private boolean gameRunning;

    @Override
    protected int getLayoutId() {
        return R.layout.run_fragment_qiangjin;
    }

    @Override
    public QiangjinFragmentPresenter getPresenter() {
        return new QiangjinFragmentPresenter();
    }

    public void changeFive(StockBloomBean stockBloomBean) {
        if (coinInfo == null) {
            return;
        }
        if (stockBloomBean != null) {

            if (boomView != null && !boomView.isCanDraw()) {
                boomView.setCanDraw(true);
            }

            switch (stockBloomBean.getStatus()) {
                case 1://准备中
                    tvAwardPoll.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment1) + stockBloomBean.getData().get(0).getPrepare().getPoolMoneyByType(coinInfo.getType()) + " " + coinInfo.getType());

                    if (iv_boom_handred.getVisibility() == View.VISIBLE) {
                        iv_boom_handred.setVisibility(View.GONE);
                        if (handredAnima != null) {
                            handredAnima.stop();
                        }

                    }
                    if (iv_boom.getVisibility() == View.VISIBLE) {
                        iv_boom.setVisibility(View.GONE);
                    }
                    if (isSubscribe) {
                        if (TextUtils.isEmpty(subscribeBetMoney) || TextUtils.isEmpty(subscribeBetValue)) {
                            return;
                        }
                        if (!isSubscriCommit) {
                            isSubscribe = false;
                            mPresenter.normalBet(subscribeBetType, subscribeBetMoney, subscribeBetValue);
                            isSubscriCommit = true;
                        }
                    }

                    boomView.gamePreparing((int) (Double.valueOf(stockBloomBean.getData().get(0).getPrepare().getSt())
                            - Double.valueOf(stockBloomBean.getData().get(0).getPrepare().getPt())));
                    break;
                case 2://游戏中
                    tvAwardPoll.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment1) + stockBloomBean.getData().get(0).getProcess().getPoolMoneyByType(coinInfo.getType()) + " " + coinInfo.getType());

                    if (boomView != null) {
                        int e = stockBloomBean.getData().get(0).getProcess().getE();
                        if (Math.abs(e - boomView.getNowTime()) > 20) {
                            boomView.supendStart(e);
                        } else {
                            boomView.gameStart();
                        }
                    }
                    isSubscriCommit = false;
                    escapeBeans = new ArrayList<>();
                    if (stockBloomBean.getData().get(2).getEscape_list().size() > 0) {
                        for (int i = 0; i < stockBloomBean.getData().get(2).getEscape_list().size(); i++) {
                            escapeBeans.add(new EscapeBean(
                                    stockBloomBean.getData().get(2).getEscape_list().get(i).getRealname()
                                    , Float.parseFloat(stockBloomBean.getData().get(2).getEscape_list().get(i).getFinal_beishu())));
                        }
                        boomView.setEscapeBeans(escapeBeans);
                    }
                    gameRunning = true;
                    break;
                case 3://游戏结束
                    tvAwardPoll.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment1) + stockBloomBean.getData().get(0).getCrash().getPoolMoneyByType(coinInfo.getType()) + " " + coinInfo.getType());

                    boomView.gameOver((float) stockBloomBean.getData().get(0).getCrash().getBoomValue());
                    if (gameRunning == true) {
                        iv_boom.setVisibility(View.VISIBLE);
                        iv_boom.start();
                    }
                    gameRunning = false;
                    break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void connectSocket(SocketBean socketBean) {
        if (socketBean != null) {
            switch (socketBean.getState()) {
                case 0:
                    if (boomView != null) {
                        boomView.setCanDraw(true);
                    }
                    break;
                case 1:
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.run_qiangjinFragment2));
                    if (boomView != null) {
                        boomView.setCanDraw(false);
                    }
                    tv_now_value.setVisibility(View.INVISIBLE);
                    tv_show_run.setVisibility(View.INVISIBLE);
                    tv_now_value.setText("");
                    tv_show_run.setText("");
                    break;
            }
        }
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
//            if (ll_wanfa_anim.getVisibility() == View.GONE) {
//                ll_wanfa_anim.setVisibility(View.VISIBLE);
//            }
            if (wanFaAnim != null) {
                wanFaAnim.stop();
                wanFaAnim.start();
            }
        } else {
            if (isSubscribe) {
                isSubscribe = false;
                subscribeBetMoney = "";
                subscribeBetValue = "";
            }
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        if (isSubscribe) {
            isSubscribe = false;
            subscribeBetMoney = "";
            subscribeBetValue = "";
        }
    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 监听网络连接，包括wifi和移动数据的打开和关闭,以及连接上可用的连接都会接到监听
            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
                //获取联网状态的NetworkInfo对象
                NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
                if (info != null) {
                    //如果当前的网络连接成功并且网络连接可用
                    if (NetworkInfo.State.CONNECTED == info.getState() && info.isAvailable()) {
                        if (boomView != null) {
                        }
                    } else {
                        if (boomView != null) {
                            if (boomView.getGameStatus() == GameStatus.STARTING) {
                                boomView.gamePause();
                            }
                        }
                    }
                }
            }
        }
    };

    @Override
    public void initView() {
        DaggerUserDataComponent.create().inject(this);
        RxBus.getDefault().register(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });
        initCoin();
        initWanfaAnim();
        initOneHandredAnim();
        initSpinner();
        initBoomView();
        initSlideTabLayout();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);

        getActivity().registerReceiver(receiver, filter);


        if (LanguageUtil.getAppLocale(App.INSTANCE) == Locale.ENGLISH) {
            ivBeBanker.setImageResource(R.mipmap.run_icon_be_banker_en);
        }
        boomView.setBoomListener(new BoomView.BoomListener() {
            @Override
            public void boom() {
                if (tv_now_value == null)
                    return;
                getActivity().runOnUiThread(() -> {
                    isBet = false;
                    isRun = false;
                    isBoom = true;
                    if (tv_now_value == null)
                        return;
                    tv_now_value.setVisibility(View.INVISIBLE);
                    tv_show_run.setVisibility(View.INVISIBLE);
                    tv_now_value.setText("");
                    tv_show_run.setText("");
                    if (userData == null) {
                        btnBet.setClickable(true);
                        btnBet.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment3));
                        btnBet.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.run_bt_10a));
                        return;
                    }
                    btnBet.setClickable(false);
                    if (isSubscribe) {
                        btnBet.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment4));
                    } else {
                        btnBet.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment3));

                    }
                    btnBet.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.run_bt_10a));
                });
            }

            @Override
            public void prePare() {
                if (tv_now_value == null)
                    return;
                getActivity().runOnUiThread(() -> {
                    isRun = false;
                    isBoom = false;
                    if (tv_now_value == null)
                        return;
                    if (userData == null) {

                        tv_now_value.setVisibility(View.INVISIBLE);
                        tv_show_run.setVisibility(View.INVISIBLE);
                        tv_now_value.setText("");
                        tv_show_run.setText("");
                        btnBet.setClickable(true);
                        btnBet.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment5));
                        btnBet.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.run_bt_10a));
                        return;
                    }

                    tv_now_value.setVisibility(View.INVISIBLE);
                    tv_show_run.setVisibility(View.INVISIBLE);
                    tv_now_value.setText("");
                    tv_show_run.setText("");
                    if (isBet) {
                        btnBet.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment4));
                        btnBet.setClickable(false);
                        btnBet.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.run_bt_10a));
                    } else {
                        btnBet.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment5));
                        btnBet.setClickable(true);
                        btnBet.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.run_bt_bg));
                    }
                });
            }

            @Override
            public void onTextChange(String nowTime) {
                if (tv_now_value == null)
                    return;
                getActivity().runOnUiThread(() -> {
                    if (btnBet == null)
                        return;
                    btnBet.setClickable(true);
                    if (Float.parseFloat(nowTime) > 100) {
                        if (iv_boom_handred.getVisibility() == View.GONE) {
                            iv_boom_handred.setVisibility(View.VISIBLE);
                            if (handredAnima != null) {
                                handredAnima.stop();
                                handredAnima.start();
                            }
                        }
                    }
                    tv_now_value.setVisibility(View.VISIBLE);
                    tv_show_run.setVisibility(View.VISIBLE);
                    btnBet.setText("");
                    if (userData == null) {
                        tv_now_value.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment6));
                        tv_show_run.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment7));
                        btnBet.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.run_bt_10a));
                        return;
                    }
                    if (!isBet) {
                        if (!isSubscribe) {
                            tv_now_value.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment6));
                            tv_show_run.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment7));
                        } else {
                            tv_now_value.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment4));
                            tv_show_run.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment8));
                        }
                        btnBet.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.run_bt_bg));
                        return;
                    }
                    if (isRun) {
                        if (!isSubscribe) {
                            tv_now_value.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment6));
                            tv_show_run.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment7));
                        } else {
                            tv_now_value.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment4));
                            tv_show_run.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment8));
                        }
                        btnBet.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.run_bt_bg));
                        return;
                    }
                    BigDecimal bet = new BigDecimal(betMoney);
                    BigDecimal time = new BigDecimal(nowTime);
                    tv_now_value.setText(bet.multiply(time) + " " + betType);
                    tv_show_run.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment9));
                    btnBet.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.run_bt_bg));
                    if (Float.parseFloat(nowTime) > betValue) {
                        btnBet.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.run_bt_bg));
                        tv_now_value.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment6));
                        tv_show_run.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment7));
                        isRun = true;
                        return;
                    }
                });

            }
        });
        ClickUtil.click(rlAssetRecord, () -> {
            if (userData == null) {
                toLogin();
                return;
            }
            ARouter.getInstance().build(RConfig.RUN_FRAGMENT_ASSET).navigation();
        });
        ClickUtil.click(rlBankerJackpot, () -> {
            if (userData == null) {
                toLogin();
                return;
            }
            ARouter.getInstance().build(RConfig.RUN_BANKER_JACKPOT).withString(Constans.MONEY_TYPE, coinInfo.getType()).navigation();
        });

        //玩法介绍点击跳转
        ClickUtil.click(ivBg, () -> ARouter.getInstance().build(RConfig.RUN_PLAY_INTEODUCE).navigation());

        tvEarn.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment10));

        etBetDispo = RxTextView.textChanges(etBet)
                .debounce(100, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .map(CharSequence::toString)
                .subscribe(s -> {
                    if (TextUtils.isEmpty(s)) {
                        s = "0";
                    }
                    if (etRunAway.getText().toString().startsWith(".")) {
                        return;
                    }
                    tvEarn.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment11) + CommonUtil.dealRunMoney(Float.parseFloat(s) * Float.parseFloat(
                            TextUtils.isEmpty(etRunAway.getText().toString()) ? "0" : etRunAway.getText().toString().trim())+""));
                });

        etRunAwayDispo = RxTextView.afterTextChangeEvents(etRunAway)
                .subscribe(edit -> {
                    String s = edit.editable().toString();
                    if (s.startsWith(".")) {
                        ToastUtil.showShort(App.INSTANCE.getString(R.string.run_qiangjinFragment12));
                        return;
                    }

                    if (coinInfo == null) {
                        return;
                    }
                    if (TextUtils.isEmpty(s)) {
                        tvEarn.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment11) + "0");
                        tvChance.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment13) + "0" + "%");
                        return;

                    }
                    if (Float.parseFloat(s) < Float.valueOf(coinInfo.getMinBeishu())) {
                        ToastUtil.showShort(App.INSTANCE.getString(R.string.run_qiangjinFragment14) + coinInfo.getMinBeishu());
                        s = coinInfo.getMinBeishu();
                        etRunAway.setText(coinInfo.getMinBeishu());
                    }
                    if (Float.parseFloat(s) > Float.valueOf(coinInfo.getMaxBeishu())) {
                        ToastUtil.showShort(App.INSTANCE.getString(R.string.run_qiangjinFragment15) + coinInfo.getMaxBeishu());
                        s = coinInfo.getMaxBeishu();
                        etRunAway.setText(coinInfo.getMaxBeishu());
                    }
                    tvEarn.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment11) + NumberUtil.keep2(Float.parseFloat(s) * Float.parseFloat(TextUtils.isEmpty(etBet.getText().toString()) ? "0" : etBet.getText().toString().trim())));
                    tvChance.setText(App.INSTANCE.getString(R.string.run_qiangjinFragment13) + NumberUtil.keep2(100 / Float.parseFloat(s.trim())) + "%");
                });

        ClickUtil.click(tvMax, () -> {
            if (userData == null) {
                toLogin();
                return;
            }
            if (coinInfo == null) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.run_qiangjinFragment16));
                mPresenter.getData();
                return;
            }
            etBet.setText(coinInfo.getMaxMoney());
        });
        ClickUtil.click(tvMin, () -> {
            if (userData == null) {
                toLogin();
                return;
            }
            if (coinInfo == null) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.run_qiangjinFragment16));
                mPresenter.getData();
                return;
            }
            etBet.setText(coinInfo.getMinMoney());

        });
        ClickUtil.click(300, tvDivide, () -> {
            if (userData == null) {
                toLogin();
                return;
            }

            if (coinInfo == null) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.run_qiangjinFragment16));
                mPresenter.getData();
                return;
            }
            if (TextUtils.isEmpty(etBet.getText().toString())) {
                return;
            }
            if (Float.parseFloat(etBet.getText().toString().trim()) / 2 < Float.parseFloat(coinInfo.getMinMoney())) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.run_qiangjinFragment17) + Float.parseFloat(coinInfo.getMinMoney()));
                etBet.setText(coinInfo.getMinMoney());
                return;
            }
            etBet.setText(Float.parseFloat(etBet.getText().toString().trim()) / 2 + "");

        });
        ClickUtil.click(300, tvMultiply, () -> {
            if (userData == null) {
                toLogin();
                return;
            }
            if (coinInfo == null) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.run_qiangjinFragment16));
                mPresenter.getData();
                return;
            }
            if (TextUtils.isEmpty(etBet.getText().toString())) {
                return;
            }
            if (Float.parseFloat(etBet.getText().toString().trim()) * 2 > Float.parseFloat(coinInfo.getMaxMoney())) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.run_qiangjinFragment18) + Float.parseFloat(coinInfo.getMaxMoney()));
                etBet.setText(coinInfo.getMaxMoney());
                return;
            }
            etBet.setText(Float.parseFloat(etBet.getText().toString().trim()) * 2 + "");
        });

        ClickUtil.click(btnBet, () -> {
            if (userData == null) {
                toLogin();
                return;
            }
            if (coinInfo == null || TextUtils.isEmpty(coinInfo.getMaxMoney()) || TextUtils.isEmpty(coinInfo.getMinMoney())) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.run_qiangjinFragment16));
                mPresenter.getData();
                return;
            }
            //准备阶段
            if (btnBet.getText().equals(App.INSTANCE.getString(R.string.run_qiangjinFragment5))) {
                checkBet(false);
                if (TextUtils.isEmpty(etRunAway.getText().toString().trim())) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.run_qiangjinFragment19));
                    return;
                }
                mPresenter.normalBet(coinInfo.getType(), etBet.getText().toString().trim(), etRunAway.getText().toString().trim());

                return;
            }
            //游戏阶段
            if (isBet) {
                if (isRun) {
                    if (isSubscribe) {
                        isSubscribe = false;
                        subscribeBetMoney = "";
                        subscribeBetValue = "";
                    } else {
                        checkBet(true);
                        subscribeBetMoney = etBet.getText().toString().trim();
                        subscribeBetValue = etRunAway.getText().toString();
                    }
                } else {
                    mPresenter.normalRun();
                }
            } else {
                if (isSubscribe) {
                    isSubscribe = false;
                    subscribeBetMoney = "";
                    subscribeBetValue = "";
                } else {
                    checkBet(true);
                    subscribeBetMoney = etBet.getText().toString().trim();
                    subscribeBetValue = etRunAway.getText().toString();
                    subscribeBetType = coinInfo.getType();
                }
            }

        });
    }

    @Override
    protected void initData() {
        mPresenter.getData();
        LiveDataBus.get().with(RxBusCode.BOOM_PUSH, StockBloomBean.class)
                .observe(this, stockBloomBean -> {
                    if (stockBloomBean != null) {
                        changeFive(stockBloomBean);
                    }
                });
    }

    private void updateText() {
        if (etBet == null || coinInfo == null)
            return;
        etBet.setText(coinInfo.getMinMoney());
        etBet.setHint(App.INSTANCE.getString(R.string.run_qiangjinFragment20) + coinInfo.getMinMoney() + "-" + coinInfo.getMaxMoney());
        etRunAway.setText(coinInfo.getEscapeBeishu());
        etRunAway.setHint(App.INSTANCE.getString(R.string.run_qiangjinFragment21) + coinInfo.getMinBeishu() + "-" + coinInfo.getMaxBeishu());
    }

    public void initCoinTab() {
        ArrayList<CustomTabEntity> tabItems = new ArrayList<>();
        Flowable.fromIterable(coinInfoList)
                .map(coinTypeBean -> new TabItem(coinTypeBean.getType(), 0, 0))
                .subscribe(tabItem -> {
                    tabItems.add(tabItem);
                });
        coinInfo = coinInfoList.get(0);
        commonTabLayoutCoin.setTabData(tabItems);
        commonTabLayoutCoin.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int pos) {
                if (!coinInfo.getType().equals(coinInfoList.get(pos).getType())) {
                    coinInfo = coinInfoList.get(pos);
                    updateText();
                }
            }

            @Override
            public void onTabReselect(int position) {
            }
        });
    }

    private void checkBet(boolean b) {
        if (TextUtils.isEmpty(etBet.getText().toString())) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.run_qiangjinFragment22));
            return;
        }
        if (TextUtils.isEmpty(etRunAway.getText().toString())) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.run_qiangjinFragment23));
            return;
        }
        if (Float.valueOf(etRunAway.getText().toString().trim()) < Float.valueOf(coinInfo.getMinBeishu())
                || Float.valueOf(etRunAway.getText().toString().trim()) > Float.valueOf(coinInfo.getMaxBeishu())) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.run_qiangjinFragment21) + coinInfo.getMinBeishu() + "-" + coinInfo.getMaxBeishu());
            return;
        }
        if (b) {
            isSubscribe = true;
        }

    }

    private void initSpinner() {
        spinnerAdapter = new QiangjinSpinnerAdapter(mainMenuBeans, getActivity());
        spinner.setAdapter(spinnerAdapter);
        spinner.setSelection(0);
//        spinner.setDropDownVerticalOffset(140);
    }

    private void initSlideTabLayout() {
        ArrayList<Fragment> fragments = new ArrayList<>();
        ArrayList<String> titles = new ArrayList<>();
        titles.add(App.INSTANCE.getString(R.string.run_qiangjinFragment24));
        titles.add(App.INSTANCE.getString(R.string.run_qiangjinFragment25));
        titles.add(App.INSTANCE.getString(R.string.run_qiangjinFragment26));
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.RUN_FRAGMENT_ALL_GUESS).navigation());
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.RUN_FRAGMENT_MY_GUESS_HISTORY).navigation());
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.RUN_FRAGMENT_OPEN_AWARD_HISTORY).navigation());
        viewPager.setOffscreenPageLimit(3);
        viewPager.setAdapter(new MyFragmentPagerAdapter(getChildFragmentManager(), titles, fragments));
        slidingTabLayout.setViewPager(viewPager);
    }


    private void initBoomView() {
        boomView.setLineTextColor(ContextCompat.getColor(App.INSTANCE, R.color.run_8e9));
        boomView.setStrokeColor(ContextCompat.getColor(App.INSTANCE, R.color.run_8e9));
        boomView.setShowTextColor(ContextCompat.getColor(App.INSTANCE, R.color.app_fff600));
        boomView.setBgColor(ContextCompat.getColor(App.INSTANCE, R.color.run_1d2));
        boomView.getLineKPaint().setColor(ContextCompat.getColor(App.INSTANCE, R.color.run_618));
        boomView.getLineTextScalePaint().setColor(ContextCompat.getColor(App.INSTANCE, R.color.run_8e9));
    }


    public void updataUI(List<CoinInfo> coinInfos) {
        coinInfoList = coinInfos;
        initCoinTab();

        updateText();

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
//        tryRecycleAnimationDrawable(boomAnimationDrawable);
//        tryRecycleAnimationDrawable(wanFaAnim);
        DisposUtil.close(etBetDispo);
        DisposUtil.close(etRunAwayDispo);
        getActivity().unregisterReceiver(receiver);

//        RxBus.getDefault().unregister(this);
    }

    private void toLogin() {
        if (!AppCircleCheckUtil.checkLogin(getActivity(), userData)) {
        }

    }

    /**
     * 下注成功
     * 按钮背景颜色变为红色
     */
    public void betSuccess(String type, String money, String escape_beishu) {
        this.isSubscribe = false;
        this.betType = type.toUpperCase();
        this.betMoney = money;
        this.betValue = Float.parseFloat(escape_beishu);
        isRun = false;
        isBet = true;
    }

    /**
     * 下注成功
     * 按钮背景颜色变为红色
     */
    public void betFail() {
        this.isSubscribe = false;
        isRun = false;
    }

    /**
     * 逃跑成功
     * 按钮文字变为 逃跑
     * 不可点击
     * 背景颜色变为绿色
     */
    public void runSuccess() {
        isRun = true;
        isBet = false;
    }

    private void initWanfaAnim() {
        wanFaAnim = new AnimationDrawable();
        Drawable drawable0 = getResources().getDrawable(R.mipmap.run_a1);
        Drawable drawable1 = getResources().getDrawable(R.mipmap.run_a2);
        Drawable drawable2 = getResources().getDrawable(R.mipmap.run_a3);
        Drawable drawable3 = getResources().getDrawable(R.mipmap.run_a4);
        Drawable drawable4 = getResources().getDrawable(R.mipmap.run_a5);
        Drawable drawable5 = getResources().getDrawable(R.mipmap.run_a6);
        Drawable drawable6 = getResources().getDrawable(R.mipmap.run_a7);
        Drawable drawable7 = getResources().getDrawable(R.mipmap.run_a8);
        Drawable drawable9 = getResources().getDrawable(R.mipmap.run_a9);
        Drawable drawable10 = getResources().getDrawable(R.mipmap.run_a10);
        Drawable drawable11 = getResources().getDrawable(R.mipmap.run_a11);
        Drawable drawable12 = getResources().getDrawable(R.mipmap.run_a12);
        Drawable drawable13 = getResources().getDrawable(R.mipmap.run_a13);
        Drawable drawable14 = getResources().getDrawable(R.mipmap.run_a14);
        Drawable drawable15 = getResources().getDrawable(R.mipmap.run_a15);
        Drawable drawable16 = getResources().getDrawable(R.mipmap.run_a16);
        wanFaAnim.addFrame(drawable0, 100);
        wanFaAnim.addFrame(drawable1, 100);
        wanFaAnim.addFrame(drawable2, 100);
        wanFaAnim.addFrame(drawable3, 100);
        wanFaAnim.addFrame(drawable4, 100);
        wanFaAnim.addFrame(drawable5, 100);
        wanFaAnim.addFrame(drawable6, 100);
        wanFaAnim.addFrame(drawable7, 100);
        wanFaAnim.addFrame(drawable9, 100);
        wanFaAnim.addFrame(drawable10, 100);
        wanFaAnim.addFrame(drawable11, 100);
        wanFaAnim.addFrame(drawable12, 100);
        wanFaAnim.addFrame(drawable13, 100);
        wanFaAnim.addFrame(drawable14, 100);
        wanFaAnim.addFrame(drawable15, 100);
        wanFaAnim.addFrame(drawable16, 100);
        wanFaAnim.setOneShot(false);
        ivBg.setImageDrawable(wanFaAnim);
        // 获取资源对象
        wanFaAnim.stop();
        // 特别注意：在动画start()之前要先stop()，不然在第一次动画之后会停在最后一帧，这样动画就只会触发一次
        wanFaAnim.start();
    }

    private void initOneHandredAnim() {
        ImageUtil.setImage(R.mipmap.run_scale_100, iv_boom_handred);
        iv_boom_handred.setVisibility(View.GONE);
    }

    private void initBoomAnim() {
        int boomTime = 210;
        boomAnimationDrawable = new AnimationDrawable();
        Drawable drawable0 = getResources().getDrawable(R.mipmap.run_b2);
        Drawable drawable1 = getResources().getDrawable(R.mipmap.run_b3);
        Drawable drawable2 = getResources().getDrawable(R.mipmap.run_b4);
        Drawable drawable3 = getResources().getDrawable(R.mipmap.run_b5);
        Drawable drawable4 = getResources().getDrawable(R.mipmap.run_b6);
        Drawable drawable5 = getResources().getDrawable(R.mipmap.run_b7);
        Drawable drawable6 = getResources().getDrawable(R.mipmap.run_b1);
        boomAnimationDrawable.addFrame(drawable0, boomTime);
        boomAnimationDrawable.addFrame(drawable1, boomTime);
        boomAnimationDrawable.addFrame(drawable2, boomTime);
        boomAnimationDrawable.addFrame(drawable3, boomTime);
        boomAnimationDrawable.addFrame(drawable4, boomTime);
        boomAnimationDrawable.addFrame(drawable5, boomTime);
        boomAnimationDrawable.addFrame(drawable6, boomTime);
        boomAnimationDrawable.setOneShot(true);
//        iv_boom.setImageDrawable(boomAnimationDrawable);
        boomAnimationDrawable.stop();
    }

    private void initCoin() {
        //初始化一个雪花样式的fallObject


        iv_boom.setViewWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE,750));
        iv_boom.setViewHeight((int) RudenessScreenHelper.pt2px(App.INSTANCE,1600));
        FallObject.Builder builder = new FallObject.Builder(getResources().getDrawable(R.mipmap.run_icon_coin1));
        FallObject fallObject = builder
                .setSpeed(10, true)
                .setSize(100, 100, true)
                .setWind(5, true, true)
                .build();
        FallObject.Builder builder1 = new FallObject.Builder(getResources().getDrawable(R.mipmap.run_icon_coin2));
        FallObject fallObject1 = builder1
                .setSpeed(10, true)
                .setSize(100, 100, true)
                .setWind(5, true, true)
                .build();
        FallObject.Builder builder2 = new FallObject.Builder(getResources().getDrawable(R.mipmap.run_icon_coin3));
        FallObject fallObject2 = builder2
                .setSpeed(10, true)
                .setSize(100, 100, true)
                .setWind(5, true, true)
                .build();

        iv_boom.addFallObject(fallObject, 40);//添加50个下落物体对象
        iv_boom.addFallObject(fallObject1, 40);//添加50个下落物体对象
        iv_boom.addFallObject(fallObject2, 30);//添加50个下落物体对象

    }


}
